package com.xstudio.pvzreborn.data.custom;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.xstudio.pvzreborn.PVZReborn;
import com.xstudio.pvzreborn.recipe.machine.SPCRecipe;
import com.xstudio.pvzreborn.utils.Utils;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import org.jetbrains.annotations.NotNull;

import java.util.function.Consumer;

public class SPCFinishedRecipe extends BaseFinishedRecipe<SPCRecipe> {

	public SPCFinishedRecipe(SPCRecipe recipe) {
		super(recipe);
	}

	@Override
	public void serializeRecipeData(@NotNull JsonObject pJson) {
		JsonArray inputArray = new JsonArray(4);
		for (Ingredient input : recipe.getInputs()) {
			inputArray.add(input.toJson());
		}
		pJson.add("inputs", inputArray);
		pJson.add("output", Utils.serializeStack(recipe.getResultItem()));
		pJson.addProperty("requireEnergy", recipe.getRequireEnergy());
		pJson.addProperty("tick", recipe.getTick());
	}

	@Override
	public String getTypeId() {
		return SPCRecipe.TYPE_ID;
	}

	public static class Builder {

		private final Ingredient[] inputs;
		private ResourceLocation id;
		private ItemStack output;
		private int requireEnergy;
		private int index;
		private int tick;

		private Builder(int length) {
			inputs = new Ingredient[length];
		}

		public static Builder of(int length) {
			if (length > 4) {
				return new Builder(4);
			}
			return new Builder(length);
		}

		public Builder id(ResourceLocation id) {
			this.id = id;
			return this;
		}

		public Builder id(String id) {
			return this.id(PVZReborn.prefix(id));
		}

		public Builder output(Item output) {
			this.output = output.getDefaultInstance();
			return this.id(output.getRegistryName().getPath());
		}

		public Builder output(ItemStack output) {
			this.output = output;
			this.id(output.getItem().getRegistryName().getPath());
			return this;
		}

		public Builder addInput(Ingredient input) {
			if (index > -1 && index < inputs.length) {
				this.inputs[index] = input;
				index++;
			}
			return this;
		}

		public Builder addInput(ItemStack input) {
			return addInput(Ingredient.of(input));
		}

		public Builder addInput(ItemLike input) {
			return addInput(Ingredient.of(input));
		}

		public Builder requireEnergy(int requireEnergy) {
			this.requireEnergy = requireEnergy;
			return this;
		}

		public Builder tick(int tick) {
			this.tick = tick;
			return this;
		}

		public void build(Consumer<FinishedRecipe> consumer) {
			new SPCFinishedRecipe(new SPCRecipe(id, output, inputs, requireEnergy, tick)).save(consumer);
		}
	}

}
